package com.flux.utils

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Environment

import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

import android.provider.MediaStore


/**
 * Created by hsy on 2016/4/15.
 */
object ImageUtil {

    private val DEFAULT_MAX_WIDTH = 960
    private val DEFAULT_MAX_HEIGHT = 640
    private val DEFAULT_MAX_SIZE = 128 * 1024
    private val DEFAULT_MIN_QUALITY = 50

    @JvmOverloads
    fun getBitmapFromFile(srcPath: String, maxWidth: Int = DEFAULT_MAX_WIDTH, maxHeight: Int = DEFAULT_MAX_HEIGHT): Bitmap {
        val newOpts = BitmapFactory.Options()
        newOpts.inJustDecodeBounds = true
        BitmapFactory.decodeFile(srcPath, newOpts)//此时返回bm为空

        val w = newOpts.outWidth
        val h = newOpts.outHeight

        val hh = maxHeight.toFloat()
        val ww = maxWidth.toFloat()
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        var be = 1//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (newOpts.outWidth / ww).toInt()
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (newOpts.outHeight / hh).toInt()
        }
        if (be <= 0)
            be = 1
        newOpts.inSampleSize = be//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        newOpts.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(srcPath, newOpts)
    }

    fun saveBitmapToFile(bitmap: Bitmap, file: File) {
        var fos: FileOutputStream? = null
        try {
            fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()

        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (null != fos) {
                try {
                    fos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
    }


    fun compressBySizeAndQuality(srcPath: String): Bitmap {
        return compressBySizeAndQuality(getBitmapFromFile(srcPath))
    }

    @JvmOverloads
    fun compressBySizeAndQuality(source: Bitmap, maxSize: Int = DEFAULT_MAX_SIZE, minQuality: Int = DEFAULT_MIN_QUALITY): Bitmap {
        if (source.isRecycled) {
            throw RuntimeException("source bitmap is recycled!")
        }
        var quality = 90
        val bos = ByteArrayOutputStream()
        source.compress(Bitmap.CompressFormat.JPEG, quality, bos)
        while (bos.toByteArray().size > maxSize && quality > minQuality) {
            quality -= 10
            bos.reset()
            source.compress(Bitmap.CompressFormat.JPEG, quality, bos)
        }
        val bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().size)
        if (!source.isRecycled) {
            source.recycle()
        }
        return bitmap
    }

    /**
     * 保存图片到相册
     * @param bmp 要保存的Bitmap
     */
    fun saveImageToGallery(bmp: Bitmap): Uri {
        // 首先保存图片
        val appDir = File(Environment.getExternalStorageDirectory(), "葵花宝")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        val file = File(appDir, fileName)
        saveBitmapToFile(bmp, file)
        LogUtil.i("图片保存:" + "图片路径:" + file.absolutePath)
        return Uri.parse("file://" + file.absolutePath)
    }

    /**
     * 删除图片
     * @param context   上下文
     * @param file      图片文件
     */
    fun deleteImage(context: Context, file: String) {
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val mContentResolver = context.contentResolver
        val where = MediaStore.Images.Media.DATA + "='" + file + "'"
        mContentResolver.delete(uri, where, null)
        context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)))
    }
}